import React, {useEffect, useRef, useState} from 'react'
import { PageHeader,Steps,Button,Form,Input,Select,message,notification} from 'antd';
import style from "./News.module.css";
import axios from "axios";
import NewsEditor from "../../../components/news-manager/NewsEditor";
const {Option}=Select
const { Step } = Steps;
export default function NewsUpdate(props) {
    const [current,setCurrent]=useState(0)
    const [category,setCategory]=useState([])
    const [formInfo,setformInfo] = useState({})//新闻标题与标签
    const [content,setContent] = useState("")//内容
    const NewsForm=useRef(null)
    const id = props.match.params.id;
    useEffect(()=>{
        axios.get('./categories').then(res=>{
            setCategory(res.data)
        })
    },[])
    useEffect(()=>{
        axios.get(`/news/${id}?_expand=category&_expand=role`).then(res=>{//获取新闻内容
            const {title,categoryId,content}  = res.data
            NewsForm.current.setFieldsValue({//利用ref，将新闻的标题和类别显示到表单中
                title,
                categoryId
            })
            setContent(content)
        })
    },[id])
    const handleNext=()=>{
        /*
        *   表单验证
        *   通过ref获取表单dom，对表单内容进行验证
        * */
        if(current===0) {
            NewsForm.current.validateFields().then(res=>{
                setformInfo(res)
                setCurrent(current+1)
            }).catch(error=>console.log(error))
        }
        else {
            if(content===""||content.trim()==="<p></p>")//trim 去掉首尾空字符
                message.error("新闻内容不能为空")
            else{
                setCurrent(current+1)
            }
        }
    }
    const handleSave=(auditState)=>{
        axios.patch(`/news/${id}`,{
            ...formInfo,
            "content":content,
            "auditState":auditState,//0  保存到草稿箱   1   待审核   2   审核通过    3拒绝审核
        }).then(res=>{
            if(auditState===0) {
                props.history.push("/news-manage/draft")
            }
            else {
                props.history.push("/news-manage/category")
            }
            notification.info({
                message: "通知",
                description:
                    `您可以在${auditState?"审核列表":"草稿箱"}中查看新闻`
            });
        })
    }

    return (
        <div>
            <PageHeader
                className="site-page-header"
                title="更新新闻"
                onBack={()=>props.history.goBack()}
            />
            <Steps current={current}>
                <Step title="基本信息" description="新闻标题、新闻分类" />
                <Step title="新闻内容"  description="新闻主体内容" />
                <Step title="新闻提交" description="保存草稿或者提交审核" />
            </Steps>
            <div style={{marginTop:"50px"}}>
                <div className={current===0?"":style.isActive}>
                    {/*模块化css*/}
                    <Form name="basic" ref={NewsForm} >
                        <Form.Item
                            label="新闻标题"
                            name="title"
                            rules={[{ required: true, message: '请输入标题' }]}>
                            <Input/>
                        </Form.Item>
                        <Form.Item name="categoryId" label="新闻分类" rules={[{ required: true }]}>
                            <Select placeholder="选择一个新闻分类">
                                {
                                    category.map(item=>{
                                        return <Option key={item.id} value={item.id} >{item.title}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                    </Form>
                </div>
                <div className={current===1?"":style.isActive}>
                    <NewsEditor content={content} getContext={(item)=>{setContent(item)}} ></NewsEditor>
                    {/*    子组件调用父组件传入的函数，进行子传父*/}
                </div>
                <div className={current===2?"":style.isActive}>
                </div>
            </div>
            <div style={{marginTop:"50px"}}>
                {
                    current===2&&<span>
                        <Button type="primary" onClick={() =>handleSave(0)}>
                        保存草稿箱
                        </Button>
                        <Button type="danger" onClick={() => handleSave(1)}>
                        提交审核
                        </Button>
                    </span>
                }
                {current<2&&<Button type="primary" onClick={()=>handleNext()}>下一步</Button>
                }
                {
                    current>0&&<Button onClick={() => {setCurrent(current-1)}}>上一步</Button>
                }

            </div>
        </div>
    )
}
